package com.SFA.OrderManagement;

import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.FrameWork.Common.BitmapManager;
import com.FrameWork.Common.CommonFunction;
import com.FrameWork.Entity.CustomerInfoEntity;
import com.FrameWork.Entity.ImagesEntity;
import com.FrameWork.Entity.OrderEntity;
import com.FrameWork.Entity.OrderLine;
import com.FrameWork.Entity.ProductEntity;
import com.FrameWork.Utils.Utils;
import com.SFA.R;
import com.SFA.ProductShow.ProductPhotoList;

public class OrderLineFragment extends Fragment implements OnClickListener{

	private View mContentView;
	private ImageButton btnAdd;
	private List<ProductEntity> list = new  ArrayList<ProductEntity>();
	private ListView listProduct = null;
	private OrderEntity entity = null;
	private CustomerInfoEntity info = null;
	private BaseAdapter adapter = null;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		if(savedInstanceState != null) {
			entity = (OrderEntity)savedInstanceState.getSerializable("ORDERENTITY");
			adapter = new ProductListAdapter();
			listProduct.setAdapter(adapter);
			ComputeHeight();
		}

	}



	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContentView = inflater.inflate(R.layout.orderline, null);
		mContentView.setDrawingCacheEnabled(false);
		btnAdd = (ImageButton)mContentView.findViewById(R.id.btnAdd);
		listProduct= (ListView)mContentView.findViewById(R.id.listProduct);
		btnAdd.setOnClickListener(this);
		return mContentView;
	}

	@Override
	public void onSaveInstanceState (Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("DATA", (Serializable)list);
		outState.putSerializable("ORDERENTITY", entity);
	}


	@Override
	public void onClick(View v) {
		if(v == btnAdd)
		{
			Intent intent = new Intent(getActivity(),SelectProductActivity.class);
			intent.putExtra("CUSTOMER", info);
			intent.putExtra("DATA", (Serializable)list);
			this.startActivityForResult(intent,100);
		}
		else
		{
			//遍历
			//ConfirmOrderFragment fragment = (ConfirmOrderFragment) getFragmentManager().findFragmentById(R.id.frag_delivery);
			//fragment.LoadData(getEntity());
		}
	}

	public void SetProductList(Intent intent)
	{
		list = (List<ProductEntity>)intent.getSerializableExtra("DATA");
		if(list ==null)
			return;
		for(ProductEntity product :  list)
		{
			boolean exist= false;
			for(OrderLine line :  OrderLineFragment.this.entity.Lines)
			{
				if(product.ID.equals(line.Product.ID))
				{
					exist = true;
					break;
				}
			}

			if(!exist)
			{
				OrderLine line = new OrderLine();
				line.Product = product;
				line.PRODUCT_ID = product.ID;
				OrderLineFragment.this.entity.Lines.add(line);

			}
		}

		List<OrderLine> temp =new ArrayList<OrderLine>();
		//查找不存在的产品，从订单明细中删除
		for(OrderLine line :  OrderLineFragment.this.entity.Lines)
		{
			boolean exist = false;
			for(ProductEntity product :  list)
			{
				if(product.ID.equals(line.PRODUCT_ID))
				{
					exist = true;
					break;
				}
			}
			//不存在以及不能是已下单的订单行
			if(!exist && line.OrderLineStatus != "1" )
			{
				temp.add(line);

			}
		}
		for(OrderLine line :  temp)
		{
			OrderLineFragment.this.entity.Lines.remove(line);
		}
		temp = null;
		System.gc();
		if(adapter == null)
		{
			adapter = new ProductListAdapter();
			listProduct.setAdapter(adapter);
		}
		else
		{
			adapter.notifyDataSetChanged();
		}
		ComputeHeight();
	}


	private void ComputeHeight()
	{
		//计算高度
		int totalHeight = 0;
		for (int i = 0; i < adapter.getCount(); i++) {
			View listItem = adapter.getView(i, null, listProduct);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();

		}

		ViewGroup.LayoutParams params = listProduct
				.getLayoutParams();
		params.height = totalHeight
				+ (listProduct.getDividerHeight() * (adapter
						.getCount() - 1));
		listProduct.setLayoutParams(params);
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode ==100)
		{
			SetProductList(data);
		}
	}



	public boolean Check()
	{
		// 判断是否添加过商品
		if(entity.Lines.size()==0)
		{
			CommonFunction.ShowDialog(getActivity(), "没有添加商品无法进行结算");
			return false;
		}
		for(int i=0;i<entity.Lines.size();i++)
		{
			OrderLine line = entity.Lines.get(i);
			if(line.QUANTITY_ORDERED ==0)
			{
				CommonFunction.ShowDialog(getActivity(), "请检查订单数量的输入，谢谢！");
				return false;
			}
		}
		//判断商品添加是否符合规范
		return true;
	}

	public void setData(OrderEntity entity, CustomerInfoEntity  info)
	{
		this.entity = entity;
		this.info = info;
		for(OrderLine orderline:entity.Lines)
		{

			//获取产品的entity
			orderline.Product = new OrderManager().getProductEntityByProductId(this.getActivity(),orderline.PRODUCT_ID);
			list.add(orderline.Product );
			if(orderline.LINE_AMOUNT>0)
				orderline.Product.PIECE_PRICE=orderline.LINE_AMOUNT/orderline.QUANTITY_ORDERED;
			orderline.PRODUCT_ID = orderline.Product.ID;
			orderline.ORDER_NO=entity.ORDER_NO;

		}
		if(adapter == null)
		{
			adapter = new ProductListAdapter();
			listProduct.setAdapter(adapter);
			ComputeHeight();
		}


	}

	public OrderEntity getEntity()
	{
		//刷新所有的订单行
		float totalAmount=0;
		int totalQuantity=0;
		for(OrderLine line:entity.Lines)
		{
			totalQuantity+=line.QUANTITY_ORDERED;
			line.LINE_AMOUNT = line.QUANTITY_ORDERED*line.Product.PIECE_PRICE;
			totalAmount+= line.LINE_AMOUNT ;
		}
		entity.TOTAL_AMOUNT = totalAmount;
		entity.TOTAL_QUANTITY = totalQuantity;
		return entity;
	}

	public class ProductListAdapter extends BaseAdapter
	{

		public  final ExecutorService pool= Executors.newFixedThreadPool(1);
		private LayoutInflater inflater= LayoutInflater.from(OrderLineFragment.this.getActivity());
		private int size=0;
		@Override
		public int getCount() {
			if(entity == null || entity.Lines == null)
				return 0;
			return entity.Lines.size();
		}

		@Override
		public OrderLine getItem(int position) {
			if(entity == null || entity.Lines == null || position>= entity.Lines.size())
				return null;
			return entity.Lines.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null)
			{

				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.order_line_item, null);
				holder.btnAction = (Button) convertView.findViewById(R.id.btnAction);
				holder.txtAmount = (EditText) convertView.findViewById(R.id.txtAmount);
				holder.txtDescription = (TextView) convertView.findViewById(R.id.txtDescription);
				holder.txtQuantity = (EditText) convertView.findViewById(R.id.txtQuantity);
				holder.subTotal=(TextView) convertView.findViewById(R.id.subtotal);
				holder.btnProduct=(ImageButton) convertView.findViewById(R.id.btnProduct);
				holder.btnAction.setOnClickListener(listener);
				holder.btnProduct.setOnClickListener(listener);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}
			if(size==0)
			{
				holder.btnProduct.measure(0, 0);
				size = holder.btnProduct.getMeasuredWidth();
			}

			final OrderLine line = this.getItem(position);
			holder.line = line;

			//控制删除按钮是否显示
			if(!"0".equals(line.OrderLineStatus))
			{
				holder.btnAction.setVisibility(View.GONE);
			}
			else
			{
				holder.btnAction.setVisibility(View.VISIBLE);
				holder.btnAction.setTag(position);
			}
			//是否显示删除按钮
			holder.txtAmount.removeTextChangedListener(holder);

			holder.txtQuantity.removeTextChangedListener(holder);
			holder.txtAmount.setSelectAllOnFocus(true);
			holder.txtQuantity.setSelectAllOnFocus(true);
			holder.txtDescription.setText("[" +  line.Product.CODE + "]" + line.Product.SHORTDESCRIPTION);
			DecimalFormat fnum = new DecimalFormat("##0.00"); 
			String dd=fnum.format(line.Product.PIECE_PRICE); 
			holder.txtAmount.setText(dd);
			holder.txtQuantity.setText(line.QUANTITY_ORDERED + "");
			holder.txtAmount.addTextChangedListener(holder);
			holder.txtQuantity.addTextChangedListener(holder);
			dd=fnum.format(line.LINE_AMOUNT); 
			holder.subTotal.setText(dd);
			holder.btnProduct.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
					intent.putExtra("DATA", line.Product);
					getActivity().startActivity(intent);
				}
			});
			//设置产品照片
			holder.future = pool.submit(holder);
			//根据订单行的状态做控制,包括控制最大值,最小值
			if(line.OrderLineStatus.equals("5"))
			{
				holder.txtAmount.setEnabled(false);
				holder.txtQuantity.setEnabled(false);
			}
			else
			{
				holder.txtAmount.setEnabled(true);
				holder.txtQuantity.setEnabled(true);
			}
			return convertView;
		}



		@SuppressLint("HandlerLeak")
		public class ViewHolder extends Handler implements TextWatcher,Runnable
		{

			public EditText txtQuantity;
			public EditText txtAmount;
			public TextView txtDescription;
			public TextView subTotal;
			public Button btnAction;
			public ImageButton btnProduct;
			public OrderLine line;
			Future<?> future;
			
			@Override
			public void handleMessage(Message msg)
			{
				if(msg != null && msg.obj != null)
				{
					btnProduct.setImageBitmap((Bitmap)msg.obj);
				}
			}


			@Override
			public void run()
			{

				//获取该产品的第一张照片
				List<ImagesEntity> list = ProductPhotoList.getPhotoInfoList(getActivity(), Integer.parseInt(line.PRODUCT_ID));
				for(ImagesEntity image : list)
				{
					if(Utils.Exist(BitmapManager.DIR + "/" + image.getName()))
					{
						Bitmap bitmap = BitmapManager.getResizedImage(BitmapManager.DIR + "/" + image.getName(), 90,90);
						Message msg = new Message();
						msg.obj= bitmap;
						this.sendMessage(msg);
						System.gc();
						break;
					}
				}
				list = null;
			}
			
			
			


			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {


			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {


			}

			@Override
			public void afterTextChanged(Editable s) {
				setText();

			}


			public void setText()
			{
				String quantity =txtQuantity.getText().toString();
				if(!TextUtils.isEmpty(quantity))
				{
					line.QUANTITY_ORDERED = Integer.parseInt(quantity);
				}
				String amount = txtAmount.getText().toString();
				if(!TextUtils.isEmpty(amount))
				{
					line.Product.PIECE_PRICE = Float.parseFloat(amount);
				}
				if(!TextUtils.isEmpty(quantity)&&!TextUtils.isEmpty(amount)){
					try {
						float line_amount = (float) Utils.convert(line.QUANTITY_ORDERED* line.Product.PIECE_PRICE);
						DecimalFormat fnum = new DecimalFormat("##0.00"); 
						String dd=fnum.format(line_amount); 
						subTotal.setText(dd);
						line.LINE_AMOUNT =line_amount;
					} catch (Exception e) {
						line.LINE_AMOUNT =0;
						subTotal.setText("0.0");
					}
				}
				else{
					subTotal.setText("0.0");
				}
				onClick(null);
			}
		}


		private OnClickListener listener = new OnClickListener()
		{

			@Override
			public void onClick(final View v) {
				if(v.getId() == R.id.btnAction)
				{
					//判断当前订单明细的状态，然后做控制。
					int index = Integer.parseInt(v.getTag().toString());
					OrderLine line = entity.Lines.get(index);
					if(!"0".equals(line.OrderLineStatus) )
					{
						return;
					}

					new AlertDialog.Builder(getActivity()).setTitle("提示")
					.setMessage("您确认删除商品" + line.Product.DESCRIPTION  +"吗?")
					.setPositiveButton("删除", 
							new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which) 
						{
							int location = Integer.parseInt(v.getTag().toString());
							for(ProductEntity product:list)
							{
								if(product.ID.equals(entity.Lines.get(location).Product.ID))
								{
									list.remove(product);
									break;
								}
							}
							entity.Lines.remove(location);
							adapter.notifyDataSetChanged();
							//通知计算订单总额
							OrderLineFragment.this.onClick(null);
							ComputeHeight();
						}
					}).setNegativeButton(R.string.CANCEL, null).create().show();
				}
				else
				{

				}
			}
		};

	}}